package com.example.http.httpclient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Map;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpConnectionManager;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HttpClientUtils {
	private final Logger logger=LoggerFactory.getLogger(getClass());
	private static HttpConnectionManager connectionManager=null;
    private static int defaultMaxConnPerHost = 30;
    private  static int defaultMaxTotalConn = 80;
    /** 连接超时时间，由bean factory设置，缺省为8秒钟 */
    private static int defaultConnectionTimeout= 8000;
    /** 默认等待HttpConnectionManager返回连接超时（只有在达到最大连接数时起作用）：1秒*/
    private static final long defaultHttpConnectionManagerTimeout = 3 * 1000;
	public static HttpConnectionManager getManager(){
		if(connectionManager==null){
			connectionManager = new MultiThreadedHttpConnectionManager();
		    connectionManager.getParams().setDefaultMaxConnectionsPerHost(defaultMaxConnPerHost);
		    connectionManager.getParams().setMaxTotalConnections(defaultMaxTotalConn);
		}
		return connectionManager;
	}

	public String get(String url,String param){
		
		HttpClient client=new HttpClient(getManager());
		client.getHttpConnectionManager().getParams().setConnectionTimeout(defaultConnectionTimeout);
		client.getParams().setConnectionManagerTimeout(defaultHttpConnectionManagerTimeout);
		GetMethod getMethod=new GetMethod(url+"?"+param);
		getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,new DefaultHttpMethodRetryHandler());
		getMethod.getParams().setCredentialCharset("utf-8");
	//	getMethod.setRequestHeader("Connection", "close");
		try {
			int status=client.executeMethod(getMethod);
			if(status==HttpStatus.SC_OK){
			  InputStream input=getMethod.getResponseBodyAsStream();
			  BufferedReader reader=new BufferedReader(new InputStreamReader(input,getMethod.getRequestCharSet()));
			  String tempbf; 
			  StringBuffer html=new StringBuffer(100); 
			  while((tempbf=reader.readLine())!=null){ 
			  html.append(tempbf); 
			  }
			  input.close();
			  return html.toString();
			}else{
				logger.error("http get请求返回的是："+getMethod.getStatusLine());
				return null;
			}
		} catch (HttpException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			getMethod.releaseConnection();
		}
		
		return null;
	}
	
	public String post(String url,Map<String,String> map){
		String html = "";
		HttpClient httpClient = new HttpClient(getManager());
		httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(defaultConnectionTimeout);
		httpClient.getParams().setConnectionManagerTimeout(defaultHttpConnectionManagerTimeout);
        PostMethod postMethod = new PostMethod(url);
        postMethod.setRequestHeader("accept", "*/*");
        postMethod.setRequestHeader("connection", "Keep-Alive");
        postMethod.setRequestHeader("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
        postMethod.setRequestHeader("Accept-Language", "zh-cn,zh;q=0.5");
        // postMethod.setRequestHeader("Accept-Encoding", "gzip,deflate");
        // postMethod.setRequestHeader("Content-Type", "text/html;charset=utf-8");
        
        NameValuePair[] data = generatNameValuePair(map);
        // 将表单的值放入postMethod中
        postMethod.setRequestBody(data);
        // 执行postMethod
        try {
			int statusCode = httpClient.executeMethod(postMethod);
			 if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
		            // 从头中取出转向的地址
		            Header locationHeader = postMethod.getResponseHeader("location");
		            String location = null;
		            if (locationHeader != null) {
		                location = locationHeader.getValue();
		                System.out.println("The page was redirected to:" + location);
		            } else {
		                System.err.println("Location field value is null.");
		            }
		            return html;
		        }
			 if(statusCode==HttpStatus.SC_OK){
				    BufferedReader in = new BufferedReader(new InputStreamReader(postMethod.getResponseBodyAsStream(), postMethod
			                .getResponseCharSet()));
			        StringBuffer sb = new StringBuffer();
			        int chari;
			        while ((chari = in.read()) != -1) {
			            sb.append((char) chari);
			        }
			        html = sb.toString();
			        in.close();
			        return html;
			 }
		} catch (HttpException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			postMethod.releaseConnection();
		}
      
      return null;
	}
	
	protected   static NameValuePair[] generatNameValuePair(Map<String, String> map) {
        NameValuePair[] nameValuePair = new NameValuePair[map.size()];
        int i = 0;
        for (Map.Entry<String, String> entry : map.entrySet()) {
            nameValuePair[i++] = new NameValuePair(entry.getKey(), entry.getValue());
        }

        return nameValuePair;
    }
}
